package com.shjn.squirrel.utils;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

/**
 * 获取GPS数据工具类
 */
public class GPSUtils {

    private static OnLocationChangedListener locationChangedListener;
    private static LocationManager locationManager;
    private static LocationListener locationListener;

    public interface OnLocationChangedListener {
        void onLocationChanged(Location location);
    }

    private GPSUtils() {
    }

    /**
     * 开启GPS数据监听器
     *
     * @param context
     */
    public static void startGPSListener(Context context, OnLocationChangedListener listener) {
        locationChangedListener = listener;
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                if (locationChangedListener != null) {
                    locationChangedListener.onLocationChanged(location);
                }
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
        }
    }

    /**
     * 移除GPS数据监听器
     */
    public static void removeGPSListener() {
        if (locationManager != null) {
            locationManager.removeUpdates(locationListener);
            locationManager = null;
            locationListener = null;
        }
    }

    /**
     * 获取经度
     *
     * @return
     */
    public static double getLongitude() {
        if (locationManager != null && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            return locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude();
        }
        return 0.0;
    }

    /**
     * 获取纬度
     *
     * @return
     */
    public static double getLatitude() {
        if (locationManager != null && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            return locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude();
        }
        return 0.0;
    }
}
